package com.thanhloyal.exchanger;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Random;

import com.example.exchanger.R;

import android.content.Context;
import android.graphics.Typeface;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MainCurListViewAdapter extends BaseAdapter {
	private Currency sourceCurrrency; 
	private String sourceCurCode;  // Get it once for faster calculation
	
	private double inputAmount;
	
	//private ArrayList<Currency> currenciesList = null;
	private ArrayList<RateHolder> rateHoldersList = null;
	private ArrayList<RateDataItem> ratesDataList = null;
	
	private Context mContext = null;
	private Typeface arialRoundedBold = null;
	private Typeface segoeuib = null;
	private Typeface britalicBold = null;
	
	public MainCurListViewAdapter(Context mContext, ArrayList<RateHolder> rateHolderList ) {
		super();
		this.rateHoldersList = rateHolderList;
		this.mContext = mContext;
		
		arialRoundedBold = Typeface.createFromAsset(mContext.getAssets(), "arial_rounded_bold.ttf");
		segoeuib =  Typeface.createFromAsset(mContext.getAssets(), "segoeuib.ttf");
		britalicBold = Typeface.createFromAsset(mContext.getAssets(), "britalic_bold.TTF");
	}
	
	
	

	
	public void setRatesDataList(ArrayList<RateDataItem> ratesDataList) {
		this.ratesDataList = ratesDataList;
	}


	public double getInputAmount() {
		return inputAmount;
	}

	public void setInputAmount(double inputAmount) {
		this.inputAmount = inputAmount;
	}

	public Currency getSourceCurrrency() {
		return sourceCurrrency;
	}

	public void setSourceCurrrency(Currency sourceCurrrency) {
		this.sourceCurrrency = sourceCurrrency;
		this.sourceCurCode = sourceCurrrency.getCurrencyCode();
	}


	public void calculateRates() {
		if(this.ratesDataList == null){
			Log.e("Loyal", "There is no data rates set.");
			return;
		}
		Log.v("Loyal", "Calculating rates with "+sourceCurCode+" as source currency");
		for (int i = 0; i < rateHoldersList.size(); i++) {
			RateHolder destBundle = rateHoldersList.get(i);
			calculateRateItem(destBundle);
		}
	}
	
	
	private void calculateRateItem(RateHolder destBundle) {
		
		Currency source = this.sourceCurrrency; // shorter name;
		if(sourceCurCode.equalsIgnoreCase(destBundle.getCurrency().getCurrencyCode())){
			Log.i("Loyal", "Got a itself case, code is: " + sourceCurCode);
			destBundle.setAskRate(1.0);
			destBundle.setBidRate(1.0);
		} else {
			String destCode;
			for (int i = 0; i < ratesDataList.size(); i++) {
				destCode = destBundle.getCurrency().getCurrencyCode();
				
				// 1. Forward case
				if(sourceCurCode.equalsIgnoreCase(ratesDataList.get(i).getFirstCode()) &&
						destCode.equalsIgnoreCase(ratesDataList.get(i).getSecondCode())){
					
					destBundle.setAskRate(ratesDataList.get(i).getAskRate());
					destBundle.setBidRate(ratesDataList.get(i).getBidRate());
					
					break;
				} 
				// 2. Reverse case
				else if(sourceCurCode.equalsIgnoreCase(ratesDataList.get(i).getSecondCode()) &&
						destCode.equalsIgnoreCase(ratesDataList.get(i).getFirstCode())){
					destBundle.setAskRate(1/ratesDataList.get(i).getBidRate());
					destBundle.setBidRate(1/ratesDataList.get(i).getAskRate());
					break;
				}
				
				// 3. Brigde case
				else{
					
					//break;
				}
			}
		}
	}
	
	@Override
	public int getCount() {
		//Log.v("Loyal", "There are: " + rateHoldersList.size());
		return rateHoldersList.size();
	}

	@Override
	public Object getItem(int pos) {
		return rateHoldersList.get(pos);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Holder holder;
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.dest_currency_main_list_item, parent, false);
			holder = new Holder();
			
			ImageView flagIcon = (ImageView) convertView.findViewById(R.id.dest_cur_item_flag);
			TextView curCodeTv = (TextView)convertView.findViewById(R.id.dest_cur_item_code);
			TextView amountTv = (TextView) convertView.findViewById(R.id.dest_cur_item_amount);
			TextView curNameTv = (TextView) convertView.findViewById(R.id.dest_cur_item_cur_name);
			
			holder.flagIcon = flagIcon;
			holder.curCodeTV = curCodeTv;
			holder.curNameTv = curNameTv;
			holder.amountTv = amountTv;
			
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		Currency c = rateHoldersList.get(position).getCurrency();
		holder.flagIcon.setImageBitmap(c.getFlag());
		holder.curCodeTV.setText(c.getCurrencyCode()+"");
		holder.curCodeTV.setTypeface(britalicBold);
		holder.curNameTv.setText(c.getCurrencyName()+"");
		
		double amount = inputAmount * rateHoldersList.get(position).getBidRate();
		NumberFormat formater = new DecimalFormat("#0.0000");
		String valueStr = formater.format(amount);
		String tempValueStr = valueStr.replace(",", ".");  // make sure that this works with bot . and ,
		String intPartStr = valueStr.substring(0, tempValueStr.indexOf("."));
		String fractionPartStr = valueStr.substring(tempValueStr.indexOf("."));
		intPartStr = separateNumberString(intPartStr);
		
		holder.amountTv.setText("" + intPartStr+fractionPartStr);
		holder.amountTv.setTypeface(arialRoundedBold);
		
		return convertView; //test
	}
	
	private String separateNumberString(String numStr){
		// Log.v("Loyal", "Separating " + numStr);
		if(numStr.length() < 3){
			return numStr;
		}
		//String numReversed = new StringBuilder(numStr).toString();
		StringBuffer res = new StringBuffer("");
		int marker = 0;
		for (int i = numStr.length()-1; i >= 0 ; i--) {
			res.append(numStr.charAt(i));
			marker ++;
			if((marker%3) == 0){
				res.append(" ");
				marker = 1;
			}
		}
		return res.reverse().toString();
	}

	private static class Holder{
		public ImageView flagIcon;
		public TextView curCodeTV;
		public TextView amountTv;
		public TextView curNameTv;
		
	}

}











